package com.saas.auth.handler;

import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.admin.api.entity.SysLog;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.log.event.SysLogEvent;
import com.pig4cloud.pig.common.log.util.LogTypeEnum;
import com.pig4cloud.pig.common.log.util.SysLogUtils;
import com.pig4cloud.pig.common.security.handler.SsoLogoutSuccessHandler;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
public class PigLogoutSuccessHandler extends SsoLogoutSuccessHandler {
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		// 获取请求参数中是否包含 回调地址
		try {
			String redirectUrl = request.getParameter(REDIRECT_URL);
			if (StrUtil.isNotBlank(redirectUrl)) {
				response.sendRedirect(redirectUrl);
			} else {
				request.getRequestDispatcher(request.getRequestURI()).forward(request, response);
			}
		} finally {
			if (!Objects.isNull(authentication)) {
				SysLog logVo = SysLogUtils.getSysLog(null);
				logVo.setTitle("退出成功");
				logVo.setServiceId(authentication.getName());
				PigUser pigUser = SecurityUtils.getUser(authentication);
				logVo.setCreateBy(Objects.isNull(pigUser) ? null : pigUser.getUsername());
				logVo.setType(LogTypeEnum.NORMAL.getType());
				SpringContextHolder.publishEvent(new SysLogEvent(logVo));
			}
		}
	}
}
